package com.imoblife.brainwavestus.oldMedia;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.imoblife.brainwavestus.GroupCommonProductActivity;
import com.imoblife.brainwavestus.model.Constant;
import com.imoblife.brainwavestus.util.DebugServerPushDataUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.util.Xml;

public class LauncherMessage {

	Activity _activity;
	AsyncTask<Void, Void, Boolean> _launchermessage;

	public LauncherMessage(Activity activity) {
		_activity = activity;
		initlaunchermessage();
		_launchermessage.execute();
	}

	private void initlaunchermessage() {

		_launchermessage = new AsyncTask<Void, Void, Boolean>() {

			protected Boolean doInBackground(Void... params) {

				try {
					int sv = getServerVode();
					if (sv > getLocalVode()) {
						downloadContent();
						setLocalVode(sv);
					}

					return true;

				} catch (Exception e) {
					e.printStackTrace();
				}

				return false;
			}

			public int getServerVode() throws IOException {
				URL url;
				if (DebugServerPushDataUtil.isDebugPushDialog) {
					url = new URL(
							"https://s3.amazonaws.com/appmessage121119/tus/debug/launcher_vc.txt");
				} else {
					url = new URL(
							"https://s3.amazonaws.com/appmessage121119/tus/launcher_vc.txt");
				}
				HttpURLConnection mHttpURLConnection = (HttpURLConnection) url
						.openConnection();
				byte[] versionDate = new byte[mHttpURLConnection
						.getContentLength()];
				InputStream inputStream = mHttpURLConnection.getInputStream();
				BufferedInputStream bufferedInputStream = new BufferedInputStream(
						inputStream);
				bufferedInputStream.read(versionDate);
				bufferedInputStream.close();
				inputStream.close();
				mHttpURLConnection.disconnect();
				int version = Integer.parseInt(new String(versionDate));
				return version;
			}

			public int getLocalVode() {
				SharedPreferences preferences = _activity.getSharedPreferences(
						"launcher", 0);
				return preferences.getInt("vc" + getLang(), 0);

			}

			public int getDefaultVC() {
				try {
					PackageManager packageManager = _activity
							.getPackageManager();
					PackageInfo pi = packageManager.getPackageInfo(
							_activity.getPackageName(), 0);
					return pi.versionCode;
				} catch (Exception e) {
					return -1;
				}

			}

			public void setLocalVode(int vc) {
				SharedPreferences preferences = _activity.getSharedPreferences(
						"launcher", 0);
				preferences.edit().clear().commit();
				preferences.edit().putInt("vc" + getLang(), vc).commit();
			}

			public String getLang() {
				String lang = Locale.getDefault().toString();
				if (lang.equals("zh_CN")) {
					return "zh_cn_";
				}
				if (lang.equals("zh_TW")) {
					return "zh_tw_";
				}
				if (lang.equals("ja_JP")) {
					return "ja_jp_";
				}
				return "";
			}

			private boolean downloadContent() throws IOException,
					XmlPullParserException {
				URL url;
				if (DebugServerPushDataUtil.isDebugPushDialog) {
					url = new URL(
							"https://s3.amazonaws.com/appmessage121119/tus/debug/"
									+ getLang() + "launchermessage.xml");
				} else {
					url = new URL(
							"https://s3.amazonaws.com/appmessage121119/tus/"
									+ getLang() + "launchermessage.xml");
				}

				HttpURLConnection mHttpURLConnection = (HttpURLConnection) url
						.openConnection();
				byte[] content = new byte[mHttpURLConnection.getContentLength()];
				InputStream inputStream = mHttpURLConnection.getInputStream();
				BufferedInputStream bufferedInputStream = new BufferedInputStream(
						inputStream);
				bufferedInputStream.read(content);
				bufferedInputStream.close();
				inputStream.close();
				mHttpURLConnection.disconnect();

				SharedPreferences preferences = _activity.getSharedPreferences(
						"message", 0);

				Editor editor = preferences.edit();
				editor.clear().commit();
				ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(
						content);

				XmlPullParser parser = Xml.newPullParser();
				parser.setInput(arrayInputStream, "utf-8");

				for (int i = parser.getEventType(); i != XmlPullParser.END_DOCUMENT; i = parser
						.next()) {

					switch (i) {

					case XmlPullParser.START_TAG:

						if (parser.getName().equals("display")) {

							for (int j = 0; j < parser.getAttributeCount(); j++) {
								editor.putString(parser.getAttributeName(j),
										(parser.getAttributeValue(j).replace(
												"\\n", "\n")));
								System.out.println(parser.getAttributeName(j)
										+ ","
										+ (parser.getAttributeValue(j).replace(
												"\\n", "\n")));
							}

						} else if (parser.getName().equals("event")) {
							for (int j = 0; j < parser.getAttributeCount(); j++) {
								editor.putString(parser.getAttributeName(j),
										parser.getAttributeValue(j));
								System.out.println(parser.getAttributeName(j)
										+ "," + parser.getAttributeValue(j));
							}
						}
					}

				}
				editor.commit();
				arrayInputStream.close();
				return true;
			}

			private long format2long(String string) {

				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				try {
					java.util.Date date = dateFormat.parse(string);

					return date.getTime();

				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				return -1;

			}

			protected void onPostExecute(Boolean result) {

				if (_activity.isFinishing()) {
					return;
				}
				final SharedPreferences content = _activity
						.getSharedPreferences("message", 0);

				String eventTapy = content.getString("eventType", "");

				// ����Ϣ

				if (eventTapy.equals("0")) {

					if (getDefaultVC() < Integer.parseInt(content.getString(
							"eventVc", "0"))) {
						new AlertDialog.Builder(_activity)
								.setTitle(content.getString("messagetitle", ""))
								.setMessage(
										content.getString("messagecontent", ""))
								.setNegativeButton(
										content.getString("buttonTitle", ""),
										new OnClickListener() {

											public void onClick(
													DialogInterface dialog,
													int which) {

												Intent intent = new Intent(
														Intent.ACTION_VIEW,
														Uri.parse(content
																.getString(
																		"eventURL",
																		"")));
												try {
													_activity
															.createPackageContext(
																	"com.android.vending",
																	Context.CONTEXT_IGNORE_SECURITY
																			| Context.CONTEXT_INCLUDE_CODE);
													intent.setPackage("com.android.vending");
												} catch (NameNotFoundException e) {

												}

												_activity.startActivity(intent);
											}
										}).show();
					}

				} else if (eventTapy.equals("1")) {

					long currentTime = System.currentTimeMillis();

					String startTime = content.getString("startTime", "");

					System.out.println("startTime" + startTime);

					String endTime = content.getString("endTime", "");

					System.out.println("endTime" + endTime);

					if (format2long(startTime) <= currentTime
							&& format2long(endTime) >= currentTime) {

						int currentCount = content.getInt("currentCount", 0);

						int displaycount = Integer.parseInt(content.getString(
								"displaycount", "-1"));

						int displayinterval = Integer.parseInt(content
								.getString("displayinterval", "-1"));

						System.out.println("currentCount=" + currentCount
								+ " displaycount=" + displaycount
								+ "displayinterval=" + displayinterval);

						if ((currentCount / displayinterval <= displaycount)
								&& (currentCount % displayinterval == 0)) {

							new AlertDialog.Builder(_activity)
									.setTitle(
											content.getString("messagetitle",
													""))
									.setMessage(
											content.getString("messagecontent",
													""))
									.setNegativeButton(
											content.getString("buttonTitle", ""),
											new OnClickListener() {

												public void onClick(
														DialogInterface dialog,
														int which) {

													String eventRUL = content
															.getString(
																	"eventURL",
																	"");

													Log.d("eventRUL",
															"eventRUL="
																	+ eventRUL);

													if (eventRUL.equals("")) {
//														_activity
//																.startActivity(new Intent(
//																		_activity,
//																		SpecialsProductActivity.class));
														
														Intent discountIntent = 
																new Intent(_activity,
																		GroupCommonProductActivity.class);
														discountIntent.setAction(Constant.ACTION_SALE_GROUP_DISCOUNT);
														
														_activity.startActivity(discountIntent);
														return;
													}

													Intent intent = new Intent(
															Intent.ACTION_VIEW,
															Uri.parse(eventRUL));
													try {
														_activity
																.createPackageContext(
																		"com.android.vending",
																		Context.CONTEXT_IGNORE_SECURITY
																				| Context.CONTEXT_INCLUDE_CODE);
														intent.setPackage("com.android.vending");
													} catch (NameNotFoundException e) {

													}

													_activity
															.startActivity(intent);
												}
											}).show();

						}
						content.edit().putInt("currentCount", ++currentCount)
								.commit();
					}

				}

			}

		};

	}
}
